﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace MockupDesigner.AppItems.Commands
{
    public class ResizeCommand : ICommand
    {
        public CommandType CommandType
        {
            get { return CommandType.Undoable; }
        }

        public void Execute(object target, params object[] parameters)
        {
            Redo();
        }

        public void Redo()
        {
            ChangeValues(finalValues);
        }

        private void ChangeValues(Dictionary<DesignerItem, Rect> values)
        {
            foreach (DesignerItem item in values.Keys)
            {
                Rect rect = values[item];
                Canvas.SetTop(item, rect.Top);
                Canvas.SetLeft(item, rect.Left);
                item.Height = rect.Height;
                item.Width = rect.Width;
            }
        }

        public void Undo()
        {
            ChangeValues(initialValues);
        }

        private Dictionary<DesignerItem, Rect> initialValues;
        private Dictionary<DesignerItem, Rect> finalValues;

        public void SetInitialValues(DesignerCanvas designerCanvas, DesignerItem designerItem)
        {
            if (initialValues == null)
            {
                initialValues = new Dictionary<DesignerItem, Rect>();
                SetCurrentValues(initialValues, designerCanvas, designerItem);
            }
        }

        public void SetFinalValues(DesignerCanvas designerCanvas, DesignerItem designerItem)
        {
            if (finalValues == null)
            {
                finalValues = new Dictionary<DesignerItem, Rect>();
                SetCurrentValues(finalValues, designerCanvas, designerItem);
            }
        }

        private void SetCurrentValues(Dictionary<DesignerItem, Rect> values, DesignerCanvas designerCanvas, DesignerItem designerItem)
        {
            if (designerCanvas != null && designerItem.IsSelected)
            {
                // we only move DesignerItems
                var designerItems = designerCanvas.SelectionService.CurrentSelection.OfType<DesignerItem>();
                foreach (DesignerItem item in designerItems)
                {
                    if (!values.ContainsKey(item))
                    {
                        double left = Canvas.GetLeft(item);
                        double top = Canvas.GetTop(item);
                        double width = item.ActualWidth;
                        double height = item.ActualHeight;
                        Rect rect = new Rect(new Point(double.IsNaN(left) ? 0 : left, double.IsNaN(top) ? 0 : top), new Size(width, height));
                        values.Add(item, rect);
                    }
                }
            }
        }
    }
}
